const prizesDao = require("../dao/prizesDao");

module.exports = {
  list: async (req, res) => {
    try {
      const { activityId } = req.query;
      const [rows] = activityId
        ? await prizesDao.getByActivityId(activityId)
        : await prizesDao.getAll();
      res.json(rows);
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  add: async (req, res) => {
    try {
      const [result] = await prizesDao.add(req.body);
      const [rows] = await prizesDao.getAll(); // 返回最新奖品，可改成 getById
      res.json(rows.find((r) => r.id === result.insertId));
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  update: async (req, res) => {
    try {
      await prizesDao.update(req.body);
      const [rows] = await prizesDao.getAll();
      res.json(rows.find((r) => r.id === req.body.id));
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },

  delete: async (req, res) => {
    try {
      await prizesDao.delete(req.params.id);
      res.json(true);
    } catch (err) {
      res.status(500).json({ message: err.message });
    }
  },
};
